package com.cauli.gateway.config;

import org.springframework.context.annotation.Configuration;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Cauli
 * @date 2023/8/30 17:35
 * @description
 * 作为一个异步组件，gateway中不允许使用引起阻塞的同步调用，若使用feign进行调用就会发生错误，
 * 我们使用CompletableFuture来将同步调用转换成异步操作，但使用CompletableFuture我们需要指定线程池，
 * 否则将会使用默认的ForkJoinPool
 * 这里我们创建一个线程池，用于权限获取使用
 */
@Configuration
public class ThreadPoolConfig {
    private final BlockingQueue<Runnable> asyncSenderThreadPoolQueue = new LinkedBlockingQueue<>(10000);

    public final ExecutorService USER_ROLE_PERM_THREAD_POOL = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            Runtime.getRuntime().availableProcessors(),
            1000 * 60,
            TimeUnit.MILLISECONDS,
            this.asyncSenderThreadPoolQueue,
            new ThreadFactory() {
                private final AtomicInteger threadIndex = new AtomicInteger(0);

                @Override
                public Thread newThread(Runnable runnable) {
                    return new Thread(runnable, "RolePermExecutor_" + this.threadIndex.incrementAndGet());
                }
            });

}
